<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-date-picker
          v-model="query.orderDate"
          clearable
          type="date"
          placeholder="下单时间"
          class="filter-item"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        />
        <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.type" clearable placeholder="订单号" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          v-permission="['admin','orderDetail:list']"
          :disabled="crud.selections.length !== 1"
          class="filter-item"
          size="mini"
          type="primary"
          @click="viewOrderDetail"
        ><svg-icon :icon-class="eye" />查看订单明细</el-button>
      </crudOperation>
      <detail ref="detailList" :master-id="masterId" />
    </div>
    <!--表单组件-->
    <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="下单时间" prop="orderDate">
          <el-date-picker
            v-model="form.orderDate"
            type="datetime"
            align="right"
            :picker-options="pickerOptions"
            style="width: 370px;"
          />
        </el-form-item>
        <el-form-item label="总价" prop="totalPrice">
          <el-input v-model="form.totalPrice" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="件数" prop="quantity">
          <el-input v-model="form.quantity" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="邮费" prop="postage">
          <el-input v-model="form.postage" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="支付方" prop="postageDirect">
          <el-select v-model="form.postageDirect" clearable size="small" class="filter-item" style="width: 370px">
            <el-option v-for="item in dict.postage_direct" :key="item.key" :label="item.label" :value="parseInt(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否发货" prop="sendOff">
          <el-select v-model="form.sendOff" clearable size="small" class="filter-item" style="width: 370px">
            <el-option v-for="item in dict.bool" :key="item.key" :label="item.label" :value="parseInt(item.value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="物流公司">
          <el-input v-model="form.express" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="form.expressNo" style="width: 370px;" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.memo" type="textarea" rows="3" style="width: 370px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      size="small"
      style="width: 100%;"
      show-summary
      :summary-method="getSummaries"
      @selection-change="handleCurrentChange"
      @row-click="rowClick"
      @row-dblclick="rowDblclick"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderNo" label="订单号" width="100" fixed />
      <el-table-column prop="orderDate" label="下单时间" width="100"><!-- :formatter="dateFormat"-->
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}/{m}/{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价" type="Number">
        <template slot-scope="scope">
          <span>¥{{ scope.row.totalPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="件数" type="Number" />
      <el-table-column prop="postage" label="邮费" type="Number">
        <template slot-scope="scope">
          <span>¥{{ scope.row.postage }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="postageDirect" label="支付方">
        <template slot-scope="scope">
          <span v-for="item of dict.postage_direct" :key="item.id">
            <span v-if="item.value == scope.row.postageDirect">{{ item.label }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="express" label="物流公司" />
      <el-table-column prop="expressNo" label="物流单号" width="125px" />
      <el-table-column prop="sendOff" label="是否发货">
        <template slot-scope="scope">
          <span v-for="item of dict.bool" :key="item.id">
            <span v-if="item.value == scope.row.sendOff">{{ item.label }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column type="expand" label="更多">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="利润" prop="income">
              <template>
                <span v-if="scope.row.postageDirect==2">¥{{ scope.row.totalPrice - scope.row.postage }}</span>
                <span v-else>¥{{ scope.row.totalPrice }}</span>
              </template>
            </el-form-item>
            <el-form-item label="均价" prop="avgPrice">
              <template>
                <span v-if="scope.row.postageDirect==2">¥{{ (scope.row.totalPrice - scope.row.postage) /scope.row.quantity }}</span>
                <span v-else>¥{{ scope.row.totalPrice /scope.row.quantity }}</span>
              </template>
            </el-form-item>
            <el-form-item label="备注" prop="memo">
              <template>
                <el-popover trigger="hover" placement="top">
                  <p style="max-width: 200px">{{ scope.row.memo }}</p>
                  <span slot="reference" class="name-wrapper">
                    {{ scope.row.memo }}
                  </span>
                </el-popover>
              </template>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column v-permission="['admin','bizOrder:edit','bizOrder:del']" label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudBizOrder from '@/api/order/bizOrder'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import Locale from 'element-ui/src/mixins/locale'
import detail from './detailList'

const defaultForm = { id: null, orderNo: null, orderDate: null, quantity: null, totalPrice: null, postage: null, postageDirect: null, express: null, expressNo: null, sendOff: null, memo: null }
export default {
  name: 'BizOrder',
  components: { pagination, crudOperation, rrOperation, udOperation, detail },
  mixins: [presenter(), header(), form(defaultForm), crud(), Locale],
  // 设置数据字典
  dicts: ['postage_direct', 'bool'],
  cruds() {
    return CRUD({ title: '销售订单', url: 'api/bizOrder', sort: 'id,desc', crudMethod: { ...crudBizOrder }})
  },
  data() {
    return {
      masterId: 0,
      permission: {
        add: ['admin', 'bizOrder:add'],
        edit: ['admin', 'bizOrder:edit'],
        del: ['admin', 'bizOrder:del']
      },
      rules: {
        // id: null,: null, : null, : null, : null, : null, : null, : null, expressNo: null, sendOff: null, memo: null }
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' }
        ],
        orderDate: [
          { required: true, message: '请输入下单日期', trigger: 'blur' }
        ],
        totalPrice: [
          { required: true, message: '请输入总价', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入件数', trigger: 'blur' }
        ],
        postage: [
          { required: true, message: '请输入邮费', trigger: 'blur' }
        ],
        postageDirect: [
          { required: true, message: '请选择支付方', trigger: 'blur' }
        ],
        sendOff: [
          { required: true, message: '请选择发货情况', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'orderNo', display_name: '订单号' },
        { key: 'expressNo', display_name: '物流单号' }
      ],
      summeryColumns: [{
        prop: 'quantity',
        prefix: ''
      }, {
        prop: 'totalPrice',
        prefix: '¥'
      }, {
        prop: 'postage',
        prefix: '¥'
      }, {
        prop: 'income',
        prefix: '¥'
      }],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  computed: {
    eye: function() {
      if (this.crud.selections.length === 1) {
        return 'view'
      } else {
        // <svg-icon icon-class="password" />
        return 'eye'
      }
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }
      return true
    },
    // 合计
    getSummaries: function(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计'
          return
        }
        if (!this.summeryColumns.map(item => item.prop).includes(column.property)) {
          return
        }
        const values = data.map(item => Number(item[column.property]))
        const precisions = []
        let notNumber = true
        values.forEach(value => {
          if (!isNaN(value)) {
            notNumber = false
            const decimal = ('' + value).split('.')[1]
            precisions.push(decimal ? decimal.length : 0)
          }
        })
        const precision = Math.max.apply(null, precisions)
        if (!notNumber) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return parseFloat((prev + curr).toFixed(Math.min(precision, 20)))
            } else {
              return prev
            }
          }, 0)
          const prefix = this.summeryColumns.find(item => item.prop === column.property).prefix
          sums[index] = prefix.concat(sums[index])
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 查看订单明细
    viewOrderDetail() {
      this.$refs.detailList.dialog = true
      this.$refs.detailList.doInit()
    },
    // 单机选中
    rowClick: function(row, column, event) {
      this.$refs.table.toggleRowSelection(row)
    },
    // 双击查看详情
    rowDblclick: function(row, column, event) {
      this.setMasterId(row)
      this.viewOrderDetail()
    },
    handleCurrentChange: function(selection) {
      this.crud.selections = selection
      if (selection.length === 1) {
        const row = selection[0]
        this.setMasterId(row)
      }
    },
    setMasterId: function(row) {
      this.masterId = row.id
    }
  }
}
</script>

<style scoped>
  .table-expand {
    margin-left: 15px;
    width: 75%;
    font-size: 0;
  }
  .table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
